import React from 'react'

type FallbackRender = ({ error }: { error: Error | null }) => React.ReactElement

// 错误边界必须实用类组件
export default class ErrorBoundary extends React.Component<
  React.PropsWithChildren<{ fallbackRender: FallbackRender }>,
  { error: Error | null }
> {
  // 定义state
  state = { error: null }

  // 当子组件发生异常时调用
  static getDerivedStateFromError(error: Error) {
    return { error }
  }

  render() {
    const { error } = this.state
    const { children, fallbackRender } = this.props
    if (error) {
      return fallbackRender({ error })
    } else {
      return children
    }
  }
}
